package com.demo.doc_pdf_demo.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;


/**
 * @Description: 多个pdf文件，合并成一个pdf
 * @Author: L.Wen
 * @Date: 2021/6/25 20:54
 */
public class PdfFilesMergeUtil {

    /**
     * pdf合并拼接
     *
     * @param files      文件列表
     * @param targetPath 合并到
     * @return
     * @throws IOException
     */
    public static File mulFile2One(List<File> files, String targetPath) throws IOException {
        // pdf合并工具类
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (File f : files) {
            if (f.exists() && f.isFile()) {
                // 循环添加要合并的pdf
                mergePdf.addSource(f);
            }
        }
        // 设置合并生成pdf文件名称
        mergePdf.setDestinationFileName(targetPath);
        // 合并pdf
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        return new File(targetPath);
    }

    public static void main(String[] args) throws IOException {
        List<File> files = new ArrayList<File>();
        files.add(new File("D:\\tmpfile\\pdf\\week20210614.pdf"));
        files.add(new File("D:\\tmpfile\\pdf\\202106210000.pdf"));
        files.add(new File("D:\\tmpfile\\pdf\\223456.pdf"));
        File f = mulFile2One(files, "D:\\tmpfile\\pdf\\mul2one2.pdf");
        System.out.println(f.length());
    }

}
